const { getList: MGT, getGoodsById: MGBI, category: MC,campuls:MCA} = require('../model/goods')

const getList = async (req, res, next) => {
  const { current, pagesize, search, campuls, qualityType, sortType, sortMethod, category } = req.query

  const clist = await MC()

  if (category && !clist.some(item => item === category)) return next({
    message: '获取商品列表失败, 没有你所选择的分类',
    code: 0,
    tips: `你传递给我的 'category' 信息是 : ${ category }`
  })
  const clist_A = await MCA()
  if (campuls && !clist_A.some(item => item === campuls)) return next({
    message: '获取交易地址失败, 没有你所选择的分类',
    code: 0,
    tips: `你传递给我的 'campuls' 信息是 : ${ campuls }`
  })

  const { list, total } = await MGT(current, pagesize, search, campuls, qualityType, sortType, sortMethod, category)

  list.forEach(item => {
    // delete item.img_small_logo
    delete item.is_select
  })

  res.send({
    message: '获取商品列表成功',
    code: 1,
    yourParams: { msg: "这里是你传递过来的参数, 带给你看看 ^_^ ", current: current + '', pagesize: pagesize + '', search,campuls, qualityType: qualityType.slice(0, -2), sortType, sortMethod, category },
    list,
    total
  })
}

const getGoodsById = async (req, res, next) => {
  const { goodsId } = req.query
  const result = await MGBI(goodsId)

  if (!result) return next({
    message: `你要查询的 goods_id 为 ${ goodsId } 的商品不存在, 请仔细检查一下 'goodsId' 再次查询 ^_^`,
    code: 2,
    tips: `你传递给后端的 id 内容是 : '${ goodsId }'`
  })

  // delete result.img_small_logo
  delete result.is_select
  delete result.cart_number

  res.send({
    message: '获取商品详细信息成功',
    code: 1,
    yourParams: { msg: "这里是你传递过来的参数, 带给你看看 ^_^ ",goodsId: goodsId + ''},
    info: result
  })
}

const category = async (req, res, next) => {
  const result = await MC()

  res.send({
    message: '获取分类列表成功',
    code: 1,
    list: result
  })
}
const campuls = async (req, res, next) => {
  const result = await MCA()

  res.send({
    message: '获取交易地址成功',
    code: 1,
    list: result
  })
}
const info = async (req, res, next) => {
  const goods_id = req.query.goodsId || req.params.goodsId
  const goods = await MGBI(goods_id - 0)

  if (!goods) return res.send({
    message: '获取商品信息失败, 你查找的商品已经被下架, 请更换 goods_id 后重试',
    code: 0
  })

  res.send({
    message: '获取商品信息成功! ^_^ ',
    code: 1,
    info: goods
  })
}


module.exports = {
  getList,
  getGoodsById,
  category,
  campuls,
  info
}
